#!/bin/bash

# Network RC 前端构建优化脚本
# 作者: AI Assistant
# 用途: 优化树莓派上的前端构建性能

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 图标定义
ROCKET="🚀"
CHART="📊"
CLEAN="🧹"
GEAR="⚙️"
HAMMER="🔨"
CHECK="✅"
CROSS="❌"
FIRE="🔥"
TIME="⏱️"
MEMORY="🧠"
CPU="💻"
DISK="💾"
SPEED="⚡"
TARGET="🎯"
CELEBRATE="🎉"

# 打印带颜色的消息
print_header() {
    echo -e "\n${BLUE}═══════════════════════════════════════════════════════════════════════════════${NC}"
    echo -e "${WHITE}                           $1                           ${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════════════════════════${NC}\n"
}

print_success() {
    echo -e "${GREEN}$CHECK $1${NC}"
}

print_error() {
    echo -e "${RED}$CROSS $1${NC}"
}

print_info() {
    echo -e "${CYAN}$2 $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_progress() {
    echo -e "${PURPLE}🔄 $1${NC}"
}

# 主要功能函数
show_system_info() {
    print_info "检查系统资源..." "$CHART"
    echo -e "${CYAN}  $CPU CPU核心数: ${WHITE}$(nproc)${NC}"
    echo -e "${CYAN}  $MEMORY 可用内存: ${WHITE}$(free -h | grep Mem | awk '{print $7}')${NC}"
    echo -e "${CYAN}  $DISK 磁盘空间: ${WHITE}$(df -h . | tail -1 | awk '{print $4}')${NC}"
}

clean_build_cache() {
    print_progress "清理构建缓存..."
    rm -rf build/
    rm -rf node_modules/.cache/
    npm cache clean --force --silent 2>/dev/null
    print_success "缓存清理完成"
}

setup_environment() {
    print_progress "设置优化环境变量..."
    
    # 设置环境变量优化
    export NODE_OPTIONS="--max-old-space-size=2048"  # 限制内存使用
    export GENERATE_SOURCEMAP=false  # 禁用源码映射
    export DISABLE_ESLINT_PLUGIN=true  # 禁用ESLint插件
    export TSC_COMPILE_ON_ERROR=true  # TypeScript错误时继续编译
    export CI=false  # 禁用CI模式警告
    export UV_THREADPOOL_SIZE=2  # 限制libuv线程池大小
    
    print_success "环境配置完成"
    echo -e "${CYAN}  NODE_OPTIONS: ${WHITE}$NODE_OPTIONS${NC}"
    echo -e "${CYAN}  GENERATE_SOURCEMAP: ${WHITE}$GENERATE_SOURCEMAP${NC}"
}

run_build() {
    print_progress "开始构建..."
    echo -e "${CYAN}  构建开始时间: ${WHITE}$(date)${NC}\n"
    
    # 显示构建进度条
    echo -e "${BLUE}构建进度:${NC}"
    echo -e "${YELLOW}▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓${NC}"
    
    # 开始构建（带时间统计）
    if time npm run build; then
        print_success "构建成功完成！"
        echo -e "${CYAN}  构建结束时间: ${WHITE}$(date)${NC}"
        show_build_results
    else
        print_error "构建失败，请检查错误信息"
        exit 1
    fi
}

show_build_results() {
    print_info "构建结果统计" "$TARGET"
    echo -e "${CYAN}  构建文件大小: ${WHITE}$(du -sh build/ 2>/dev/null || echo '未找到构建文件')${NC}"
    
    if [ -d "build/static/js" ]; then
        echo -e "${CYAN}  主要JS文件:${NC}"
        ls -lh build/static/js/ | tail -n +2 | while read line; do
            echo -e "${WHITE}    $line${NC}"
        done
    fi
    
    if [ -d "build/static/css" ]; then
        echo -e "${CYAN}  主要CSS文件:${NC}"
        ls -lh build/static/css/ | tail -n +2 | while read line; do
            echo -e "${WHITE}    $line${NC}"
        done
    fi
}

# 主程序
main() {
    print_header "$ROCKET Network RC 前端构建优化器 $ROCKET"
    
    show_system_info
    echo
    
    clean_build_cache
    echo
    
    setup_environment
    echo
    
    run_build
    echo
    
    print_header "$CELEBRATE 构建优化完成！ $CELEBRATE"
}

# 执行主程序
main